
package com.rollway.restful.processor;

import com.rollway.restful.MethodMetadata;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestPart;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import static com.rollway.restful.utils.Util.checkState;


public class RequestPartParameterProcessor implements AnnotatedParameterProcessor {

	private static final Class<RequestPart> ANNOTATION = RequestPart.class;

	@Override
	public Class<? extends Annotation> getAnnotationType() {
		return ANNOTATION;
	}

	@Override
	public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
		int parameterIndex = context.getParameterIndex();
		MethodMetadata data = context.getMethodMetadata();
		checkState(data.getBodyIndex() == null, "body can only be present once");
		String value = (String) AnnotationUtils.getAnnotationAttributes(annotation).get("value");
		data.setBodyName(value);
		data.setBodyIndex(parameterIndex);
		if(!data.getHeaders().containsKey(HttpHeaders.CONTENT_TYPE)){
			data.getHeaders().put(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
		}
		return true;
	}

}
